import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;


public class HTTPConnectivity implements Runnable {
	
	ConnectionStatus internetStatus = new ConnectionStatus();
	String testURL = "http://www.example.com";
	
	public final static int MIN_PORT = 0;
	public final static int MAX_PORT = 65535;
	
	// for threads synchronization
	ResultsTable sharedTable = new ResultsTable();
	private int numTests;
	static CyclicBarrier barrier;
	String HTTP_KEY;
	
	
	public HTTPConnectivity(ResultsTable r, CyclicBarrier b, int n){
		sharedTable = r;
		barrier = b;
		numTests = n;
	}
	
	
	@Override
	public void run() {
		internetStatus = runTests(numTests);
		sharedTable.addResult(HTTP_KEY, internetStatus);
		try {
			barrier.await();
		} catch (InterruptedException e) {

		} catch (BrokenBarrierException e) {
		}
		
	}

	public ConnectionStatus runTests (int n) {
		System.out.println("In HTTP RUN for URL " + testURL);
	
			for (int i = 0; i < n; i++){
				// run the test n times
				if (isConnected()) {
					this.internetStatus.addPassedAttempt();
				} else {
					this.internetStatus.addFailedAttempt();
				}
			}			
	
		return this.internetStatus;
	}
		
	private boolean isConnected(){
		try {
			URL url = new URL(testURL);
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			urlConn.connect();
			
			if (HttpURLConnection.HTTP_OK == urlConn.getResponseCode())
				return true;
			else
				return false;
		} catch (IOException e) {
//			System.err.println("Error creating HTTP connection");
			return false;
		}
	}

	public void setProperties(String url, String key) {
		this.testURL = url; // TODO: Add URL checking
		HTTP_KEY = key;
	}
		
} // end class HTTPConnectivity